package com.bungarus.busi;

import com.bungarus.Transfer;
import com.bungarus.codec.protobuf.MessageProtobuf;
import com.bungarus.model.BungarusClientException;
import com.bungarus.model.MessageBuilder;
import com.bungarus.model.MessageType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * Created by tang on 2018/11/25.
 */
public class ProcessMessagesFromAccessHandler extends ChannelInboundHandlerAdapter {
    Logger logger = Logger.getLogger(ProcessMessagesFromAccessHandler.class);

    private final Transfer transfer;

    public ProcessMessagesFromAccessHandler(Transfer transfer) {
        this.transfer = transfer;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof MessageProtobuf.Message){
            MessageProtobuf.Message message = (MessageProtobuf.Message) msg;
            if(MessageType.HEARTBEAT_PING == message.getHeader().getType()){
                //send back pong
                ctx.writeAndFlush(MessageBuilder.buildHeartbeatPongMessage(message.getHeader().getId()));
            }
            logger.info("header of session or status messages from access layer: " + message.getHeader().toString());
            logger.info("body of session or status messages form access layer: " + message.getBody().toString());

            if (message.getHeader().getType() == MessageType.STATUS ||
                    message.getHeader().getType() == MessageType.AUTH) {
                transferSessionAndStatusMsgToAllBusi(ctx, message);
            }
        }
        else {
            super.channelRead(ctx, msg);
        }
    }

    private void transferSessionAndStatusMsgToAllBusi(ChannelHandlerContext ctx, MessageProtobuf.Message message) {
        List<BaseClient> clientList = transfer.getTransferInnerClients();
        clientList.forEach(baseClient -> {
            try {
                logger.debug("tranfer session message to busi: " + message.toString());
                baseClient.sendMessage(message, null, ctx);
            }
            catch (BungarusClientException e) {
                ctx.fireExceptionCaught(e);
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
